﻿using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using DesignerHelper.Main;
using SpreadsheetGear;
using SpreadsheetGear.Windows.Forms;

namespace WorkbookDesigner.UI
{
    public class LocateRangePresenter
    {
        public INameListView View { get; }

        public LocateRangePresenter(INameListView view)
        {
            View = view;
        }

        private WorkbookView ActiveView => View.ActiveView;
        private IWorkbook BookWorkOn => ActiveView.ActiveWorkbook;
        private IWorkbookSet Wbs => ActiveView.ActiveWorkbookSet;

        private List<ListViewItem> AllNames { get; set; }
        public List<ListViewItem> NameItemList { get; private set; }

        public string FormText => BookWorkOn != null ? $"名称定位 - {BookWorkOn.Name}" : "名称定位";

        public void TriggerInit()
        {
            INames names = BookWorkOn.Names;
            ResetNameList(names);
            SearchTextFilter();
            View.ResetListViewSize(NameItemList.Count);
        }
        private void ResetNameList(INames names)
        {
            Wbs.DoWork(() =>
            {
                AllNames = names.OfType<IName>()
                    .Where(name => name.Visible && name.RefersToRange != null)
                    .Select(GetNameItem)
                    .ToList();
            });
        }
        private void SearchTextFilter()
        {
            Wbs.DoWork(() =>
            {
                NameItemList = View.InSearchMode
                    ? AllNames.Where(item => item.SubItems[0].Text.ToUpper().Contains(View.NameToSearch.ToUpper())).ToList()
                    : AllNames;
            });

        }

        public void ActivateRange(ListViewItem item)
        {
            IName name = GetIName(item);
            if (name == null) return;
            Wbs.DoWork(() =>
            {
                name.RefersToRange?.Worksheet.Select();
                name.RefersToRange?.Select();
            });
        }

        private static IName GetIName(ListViewItem item)
        {
            return item?.Tag as IName;
        }

        private ListViewItem GetNameItem(IName name)
        {
            return
                new ListViewItem(new[]
                {name.Name, name.RefersToRange.GetAddress(true, true, ReferenceStyle.A1, true, null) ?? ""})
                {
                    Tag = name
                };
        }
    }
}
